'use strict';

const Controller = require('egg').Controller;
const BaseController = require('./base');

const mockData = require('./mock/data.js');
const fs = require('fs');
const pump = require('pump');

/**
 * 模拟通用接口
 */
class CommonController extends BaseController {
  async index() {
    const { ctx } = this;
    ctx.body = {
      code: 200,
      reqUrl: ctx.request.url,
      reqMethod: ctx.request.method,
      reqData: ctx.request.body,
      data: {
        time: new Date(),
      },
      msg: '获取成功',
    };
  }

  /**
   * @summary common 上传文件
   * @description 这是一个上传文件接口
   * @Router POST /common-api/common/upload
   */
  async upload() {

    console.log('--------upload()----------');
    const { ctx } = this;

    const parts = this.ctx.multipart({ autoFields: true });
    let files = {};
    let stream;
    console.log('parts---------', parts);
    while ((stream = await parts()) != null) {
      if (!stream.filename) {
        break;
      }
      const fieldname = stream.fieldname; // file表单的名字
      console.log('fieldname------',fieldname);

      // 上传图片的目录
      const dir = await this.service.common.getUploadFile(stream.filename);
      const target = dir.uploadDir;
      const writeStream = fs.createWriteStream(target);

      await pump(stream, writeStream);

      files = Object.assign(files, {
        [fieldname]: dir.saveDir,
      });
      console.log(dir);
    }
    ctx.body = {
      code: 200,
      reqData: ctx.request.body,
      data: files,
      // data: mockData.creatDetail(),
      msg: '上传成功',
    };
  }
}

module.exports = CommonController;
